import axios, { AxiosResponse } from "axios";
import { config } from "@/config";
import { resultType } from "@/types/res/result";
import { showLoadingToast, closeToast, showFailToast } from 'vant';
import 'vant/es/toast/style';
import { VagueOject } from "@/types/common";

interface requestParams {
    url: string,
    data: VagueOject,
    header: VagueOject
}

const instance = axios.create({
    baseURL: config.checkEnvironment(),
    timeout: 10000,
    headers: {
        "Content-Type": "application/json",
        "token":localStorage.getItem("token") == null ? "" : localStorage.getItem("token")
    }
});

instance.interceptors.request.use(
    function (config) {
        showLoadingToast({
            duration: 0,
            forbidClick: true,
            message: '加载中....',
        })
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(
    function (response) {
        closeToast()
        return ResponseCodeCheck(response.data)
    },
    function (error) {
        return Promise.reject(error);
    }
);

const ResponseCodeCheck = (response: resultType<any>) => {
    console.log("response",response)
    switch (response.status) {
        case 200:
            return response.result 
            break;

        case 404:
            showFailToast({
                message: response.message
            });
            throw new Error(response.message)
            break;

        case 500:
            showFailToast({
                message: response.message,
                onClose: () => {
                    location.href = "/#/user"
                }
            });
            throw new Error(response.message)
            break;

        default:
            break;
    }
}

export const GET = async <T>(params: requestParams): Promise<T> => {
    return await instance.get<T>(params.url, {
        params: params.data,
        headers: params.header
    })
}

export const POST = async <T>(params: requestParams): Promise<T> => {
    console.log("params",params)
    return await instance.post<T>(params.url, params.data, {
        headers:params.header
    })
}

